<?php

namespace App\Repositories;

use App\Models\LouAddress;
use App\Models\Member;
use App\Models\MemberAddress;

class AddressRepository
{

    public function getAreas($filter = null, $user_type = 0)
    {
        $types = [0];
        if ($user_type) {  //1：病患 2：职工
            $types[] = $user_type;
        } else {
            $types[] = 1;
        }

        $list = LouAddress::query()
            ->where(['status' => 1])
            ->whereIn("type", $types)
            ->when(isset($user_type), function ($q) use ($user_type) {
                if ($user_type == 2) {
                    return $q->where("level", "<", 4);
                }
            })
            ->orderBy("sort", "asc")
            ->get(['id', 'title', 'pid', 'level'])
            ->toArray();

        foreach ($list as $k => &$v) {
            if ($v['level'] == 1) {
                $v['title'] = is_numeric($v['title']) ? ($v['title'] . '号楼') : $v['title'];
            } else if ($v['level'] == 2) {
                $v['title'] = is_numeric($v['title']) ? ($v['title'] . 'F') : $v['title'];
            }
        }
        $list = list_to_tree($list, "id", "pid");

        return $list;
    }

    /**
     * 添加/编辑孩子时，地址选择
     */
    public function getAreaAddChildren($pid = 0, $type = 0)
    {
        return LouAddress::query()
            ->where(['pid' => $pid, 'type' => $type, 'status' => 1])
            ->orderBy("sort", "asc")
            ->get(['id', 'title', 'level'])
            ->toArray();
    }

    public function saveOrUpdate($id = null, $params = [])
    {
        $data['consignee'] = $params['consignee'] ?? "";
        $data['phone'] = $params['phone'] ?? "";
        $data['province_id'] = $params['province_id'] ?? "";
        $data['city_id'] = $params['city_id'] ?? "";
        $data['region_id'] = $params['region_id'] ?? "";
        $data['district'] = $params['district'] ?? "";
        $data['address'] = $params['address'] ?? "";
        $data['update_time'] = time();
        $data['uid'] = UID;

        if (!MemberAddress::query()->where(['uid' => UID, 'is_default' => 1])->count("id")) {
            $data['is_default'] = 1;
        }

        $username = Member::query()->where("id", UID)->value("username");
        if (empty($username)) {
            Member::query()->where("id", UID)->update([
                'username' => $username,
                'mobile' => $data['phone']
            ]);
        }

        if ($id) {
            MemberAddress::where("id", $id)->update($data);
            return $id;
        } else {
            $data['type'] = $params['type'] ?? 1;
            $data['create_time'] = time();
            $res = MemberAddress::create($data);
            return $res['id'];
        }
    }

    /**
     * 获取默认地址
     * @param null $id
     * @param null $uid
     */
    public function getAddressInfo($id = null, $uid = null, $condition = [])
    {
        $model = MemberAddress::query();
        if (!empty($id)) {
            $model->where(['id' => $id]);
        } else {
            $model->where(['uid' => $uid])->orderBy("is_default", "desc");
        }
        $res = $model->where($condition)->first();

        if (empty($res))
            return null;

        $res['province'] = LouAddress::query()->where(['id' => $res['province_id']])->value("title");
        is_numeric($res['province']) && $res['province'] .= '号楼';
        $res['city'] = LouAddress::query()->where(['id' => $res['city_id']])->value("title");
        is_numeric($res['city']) && $res['city'] .= 'F';
        $res['region'] = LouAddress::query()->where(['id' => $res['region_id']])->value("title");

        if (!empty($res['district'])) {
            $res['district_title'] = LouAddress::query()->where(['id' => $res['district']])->value("title");
            is_numeric($res['district_title']) && $res['district_title'] .= '床';
        }

        return $res;
    }

    //我创建的地址
    public function getMyAddress($filter, $pageNum, $pageSize)
    {
        $filter['is_delete'] = 2;
        $res = MemberAddress::query()
            ->where($filter)
            ->orderBy("id", "desc")
            ->paginate($pageSize, "*", null, $pageNum)
            ->toArray();

        $res = filterPaginateData($res);
        foreach ($res['items'] as $k => &$v) {
            $v['province'] = LouAddress::query()->where(['id' => $v['province_id']])->value("title");
            is_numeric($v['province']) && $v['province'] .= '号楼';
            $v['city'] = LouAddress::query()->where(['id' => $v['city_id']])->value("title");
            is_numeric($v['city']) && $v['city'] .= 'F';
            $v['region'] = LouAddress::query()->where(['id' => $v['region_id']])->value("title");

            if (!empty($v['district'])) {
                $v['district_title'] = LouAddress::query()->where(['id' => $v['district']])->value("title");
                is_numeric($v['district_title']) && $v['district_title'] .= '床';
            }
        }

        return $res;
    }

    /**
     * 设置默认值
     * @param null $id
     * @param null $uid
     */
    public function setDefault($id = null, $uid = null)
    {
        if (!intval($id) || !intval($uid))
            return retFail("参数异常");

        $address = MemberAddress::query()->where(['id' => $id])->first();
        if (empty($address))
            return retFail("地址异常");

        if ($address['uid'] != $uid) {
            return retFail("无权限");
        }

        MemberAddress::query()->where(['is_default' => 1, 'uid' => $uid])->update([
            'is_default' => 0,
            'update_time' => time()
        ]);

        MemberAddress::query()->where(['id' => $id])->update([
            'is_default' => 1,
            'update_time' => time()
        ]);

        return retSuc([], "修改成功");
    }


}
